<?php

namespace app\models\rabbitmq;

use PhpAmqpLib\Connection\AMQPStreamConnection;
use PhpAmqpLib\Message\AMQPMessage;

class Mq
{
    private static $instance = null;
    private $connection = null;
    private $channel = null;

    /**
     * Mq constructor.
     * @param $exchangeName
     * @param $routeKey
     */
    private function __construct()
    {
        //链接amqp
        try {
            $this->connection = new AMQPStreamConnection(
                \Yii::$app->params["rabbitmq"]["host"],
                \Yii::$app->params["rabbitmq"]["port"],
                \Yii::$app->params["rabbitmq"]["user"],
                \Yii::$app->params["rabbitmq"]["pwd"]
            );

            if ($this->connection->isConnected()) {
                //链接成功
                $this->channel = $this->connection->channel();
            }
        } catch (\Exception $e) {
            //记录错误信息
            \Yii::info("mq连接错误" . $e->getMessage(), "addlog");
        }
    }
    private function __clone()
    {
    }

    /**
     * @param $exchangeName
     * @param $routeKey
     * @return Mq|null
     */
    public static function getInstance()
    {

        if (is_null(self::$instance)) {

            self::$instance = new self();
        }

        return self::$instance;
    }

    /**
     * @param $msg
     * @return bool
     */
    public function publish($exchangeName, $routeKey, $msg)
    {
        try {
            if ($this->channel) {
                $msg = new AMQPMessage($msg);
                $this->channel->basic_publish($msg, $exchangeName, $routeKey);
            } else {
                return false;
            }
        } catch (\Exception $e) {
            //记录错误信息
            \Yii::info("mq发送消息错误" . $e->getMessage(), "addlog");
            return false;
        }
        return true;
    }
}
